package com.example.gokchinesefoodmappcdev.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.gokchinesefoodmappcdev.dao.SysRoleDao;
import com.example.gokchinesefoodmappcdev.dao.SysUserDao;
import com.example.gokchinesefoodmappcdev.entity.SysRole;
import com.example.gokchinesefoodmappcdev.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    SysUserDao userDao;
    @Autowired
    SysRoleDao roleDao;

    public final static String ROLE_PREFIX="ROLE_";

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        //先根据用户名查出对应的用户对象
        SysUser user = userDao.selectOne(wrapper);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //查询到有用户信息后，通过用户名查询拥有的角色信息
        List<SysRole> roles = roleDao.findRolesByUserName(username);

        Collection<GrantedAuthority> authorities=new HashSet<>();

        //把用户的角色名称存入权限中
        for (SysRole role : roles) {
            authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX+role.getRoleName()));
        }

        //封装UserDetails的对象数据，可以通过spring-security提供的默认用户对象
        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                //如果是noop表示不进行加密，bcrypt采用算法进行加密
                "{noop}" + user.getPassword(),
                true,
                true,
                true,
                true,
                authorities);
    }
}
